<template>
  <el-dialog
    top='23vh'
    :title="title"
    :visible.sync="visible"
    :lock-scroll='lockGao'
    @open='sendAjax'
    @close='deactivated'
    :close-on-click-modal='false'
    custom-class="salaryPassword-dialog"
    size='tiny'
    
  > 

    <!-- 默认页面 -->

    <section class="defaultView" v-if='view==="defaultView"'>
      
      <div class='blue password'>
        <el-input autofocus ref='passwordInput' type='password' :maxlength='6' :auto-complete='autoCom'  placeholder="请输入6位纯数字密码"  @keydown.native="handlePassword($event)"  @keyup.native="handlePassword($event)" v-model.trim="defaultView.password">
          <span class="blue" slot="append" @click.stop='handleSure'>确定</span>
        </el-input>
      </div>

      <p class="tipMessage">
					<el-tag
						type="danger"
						:closable="true"
						@close="defaultView.tipMessage=''"
						v-show='defaultView.tipMessage'
					>
						{{defaultView.tipMessage}}
					</el-tag>
      </p>

      <span @click.stop="forgetPassword" class="forget">忘记密码?</span>
        
    </section>
    


    <!-- 发送验证码页面 -->

    <section class="verificationView" v-if='view==="verificationView"'>
      <p class='sended'><strong> 验证码</strong>已发送到您的手机</p>
      <p class='tel'><strong>{{phoneNum | hideTel}}</strong></p>
      <div class="verification">
        <input v-model='verificationView.verification[0]' type='number' oninput="if(value.length>1)value=value.slice(0,1)" ref="Input0" v-focus  @keydown.delete="keyupAction(0)" @keydown.left="keyleftAction(0)"  @input="nextOne(0)"  maxlength='1' class='verification-input' />
        <input v-model='verificationView.verification[1]' type='number' oninput="if(value.length>1)value=value.slice(0,1)" ref="Input1" @keydown.delete="keyupAction(1)" @input="nextOne(1)" @keydown.left="keyleftAction(1)"  maxlength='1' class='verification-input' />
        <input v-model='verificationView.verification[2]' type='number' oninput="if(value.length>1)value=value.slice(0,1)" ref="Input2"  @input="nextOne(2)"  @keydown.delete="keyupAction(2)" @keydown.left="keyleftAction(2)"  maxlength='1' class='verification-input' />
        <input v-model='verificationView.verification[3]' type='number' oninput="if(value.length>1)value=value.slice(0,1)" ref="Input3"  @input="nextOne(3)"   @keydown.delete="keyupAction(3)" @keydown.left="keyleftAction(3)"  maxlength='1' class='verification-input' />
        <input v-model='verificationView.verification[4]' type='number' oninput="if(value.length>1)value=value.slice(0,1)" ref="Input4"  @input="nextOne(4)"   @keydown.delete="keyupAction(4)" @keydown.left="keyleftAction(4)"  maxlength='1' class='verification-input' />
        <input v-model='verificationView.verification[5]' type='number' oninput="if(value.length>=2) value=value.slice(0,1)" ref="Input5"  @input="nextOne(5)"   @keydown.delete="keyupAction(5)" @keydown.left="keyleftAction(5)"  maxlength='1' class='verification-input' />
        <!-- <el-input  ref="Input1" v-focus="false"  @keyup.native="nextOne(1)" :maxlength='1' class='verification-input'></el-input>
        <el-input  ref="Input2" @keyup.native="nextOne(2)" :maxlength='1' class='verification-input'></el-input>
        <el-input  ref="Input3" @keyup.native="nextOne(3)" :maxlength='1' class='verification-input'></el-input> -->
      </div>
      <p class='callHR'>收不到验证码请联系管理员</p>

    </section>



    <!-- 修改密码页面 -->

    <section class="changePasswordView" v-if='view==="changePasswordView"'>
      
      
      <p class='password'><label>密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码</label><el-input autofocus type='password' :maxlength='6' :minlength = '6' class='changePassword-input' v-model='changePasswordView.password' placeholder="请输入6位纯数字密码"></el-input></p>

      <p class='surePassword'><label>确认密码</label><el-input type='password' :maxlength='6' class='changePassword-input' v-model='changePasswordView.surePassword' placeholder="请再次输入密码"></el-input></p>

      <div class='button'>
        <el-button @click="confirmModify" type="primary">确认</el-button>
        <el-button @click="dialogVisible = false">放弃修改</el-button>
      </div>


    </section>



    <!-- 修改密码成功页面 -->

    <section class="successView" v-if='view==="successView"'>
      <img src="../../../static/images/passwordSuccess.svg" class='icon'>
      <p class='config'>密码设置完成</p>
    </section>

  </el-dialog>
</template>

<script>
import Vue from 'vue'
import { Dialog, Message, Tag } from 'element-ui'
Vue.use(Tag)
Vue.use(Dialog)

export default {
	props: {
		dialogVisible: {
			default: false
		},
		passwordStatus: {
			default: null
		},

	},

	data () {
		return {
			visible: false,
			view: 'defaultView',
			defaultView: {
				password: '',
				disabled: false,
				tipMessage: '',
				verify: false
			},
			verificationView: {
				verification: ['', '', '', '', '', ''],
				flag: true
			},
			changePasswordView: {
				password: '',
				surePassword: ''
			},
			successView: {},
			phoneNum: null,
			autoCom: 'off',
			lockGao: false,
			index: 0,

		}
	},
	filters: {
		hideTel (val) {
			return Array.from(val).fill('*', -8, -4).join('')
		}
	},
	computed: {
		title () {
			switch (this.view) {
			case 'defaultView':
				return '请输入查询密码'
				break
			case 'verificationView':
				return '请输入验证码'
				break

			case 'changePasswordView':
				return '设置密码'
				break

			case 'successView':
				return ''
				break
			}
		}
	},

	watch: {
		dialogVisible (newValue, oldValue) {
			this.visible = newValue
			this.verificationView.verification = ['', '', '', '', '', '']
			if (newValue && this.view === 'verificationView') {
				Vue.nextTick(() => {
					this.$refs.Input0.focus()
				})

			} else if (newValue && this.view === 'defaultView') {
				Vue.nextTick(() => {
					this.$refs.passwordInput.$el.children[0].focus()
				})

			}

		},
		'verificationView.verification' (newValue) {
			const inputVal = newValue.join('')
			if (this.verificationView.flag && newValue && inputVal.length == 6) {

				//  发送请求
				const params = {
					verificationCode: inputVal
				}
				this.Axios
					.Post(this.URL.verificationCodeMatching.url, params)
					.then((res) => {
						var code = res.data.datas
						if (code == 10012) {
							this.view = 'changePasswordView'
						} else {
							Message({
								message: '验证码输入错误,请重新输入',
								type: 'warning'
							})
                
							this.verificationView.flag = false
							setTimeout(() => {
								this.verificationView.flag = true
							}, 1000)

						}
					})
			}
		}
	},
	directives: {
		focus: {

			inserted (el) {
				el.focus()
			}

		}
	},



	methods: {

		handlePassword (event) {
			const reg = /^\d+$/
			let e = event ? event : window.event
			let target = e.target || e.srcElement
			if (e.key === 'Enter') {
				this.handleSure()
				return
			}
			if (!reg.test(e.key)) {
				let result = Array.from(target.value)
				result.forEach((ele, i, arr) => {
					if (!reg.test(ele)) {
						arr.splice(i, 1)
						target.value = arr.join('')
					}
				})
			}
		},

		deactivated () {
			this.$emit('update:dialogVisible', false)
			Object.assign(this.$data, this.$options.data())
		},


		keyleftAction: function (index) {

			if (index != 0) {
				this.$refs['Input' + (index - 1)].focus()
				Vue.nextTick(() => {
					this.moveToEnd(this.$refs['Input' + (index - 1)])
				})

			}

		},
		moveToEnd: function (el) {

			if (typeof el.selectionStart == 'number') {

				el.selectionStart = el.selectionEnd = 1
			} else if (typeof el.createTextRange != 'undefined') {
				el.focus()
				var range = el.createTextRange()
				range.collapse(false)
				range.select()
			}
		},

		keyupAction: function (index) {

			if (!this.verificationView.verification[index] && this.verificationView.verification[index] !== '0') {

				if (index != 0) {
					this.$refs['Input' + (index - 1)].focus()
				}

			}
		},

		nextOne: function (index) {
			if (this.verificationView.verification[index] !== '' && index < 5) {
				this.$refs['Input' + (index + 1)].focus()

			}
		},

		sendAjax () {

			// 二次密码在数据库中 显示默认页面
			// 二次密码不在数据库中 显示发送验证码页面

			if (this.passwordStatus == '10003') {
				this.view = 'defaultView'
			} else {
				this.view = 'verificationView'

				this.phoneNum = this.passwordStatus
			}
			// const FN = function(year) {
			//   this.name = 'FN1';
			//   this.age = '23';
			//   this.year = year;
			//   this.type = 'Function';
			// };

			// const FN2 = function() {
			//   this.name = 'FN2';
			//   FN.apply(this, arguments);
			// };

			// var test = new FN2(2008);

			// console.log(test.name, 'name');
			// console.log(test.age, 'age');
			// console.log(test.year, 'year');

		},

		handleSure () {
			// 校验成功
			this.checkPassword()

			if (this.defaultView.verify) {
				this.Axios.Post(this.URL.confirmation.url, { password: this.defaultView.password }).then(res => {
					const code = res.data.datas
					if (code == 10010) {
						this.deactivated()
						this.$router.push('mySalary')
					} else {
						Message({
							message: '输入密码错误，请重新输入',
							type: 'warning'
						})
					}

				})

			}
		},

		/* defaultView */

		checkPassword () {

			const reg = new RegExp(/^\d{6}$/)

			this.defaultView.verify = false

			if (this.view == 'verificationView') { return }

			if (!this.defaultView.password) {
				this.defaultView.tipMessage = '密码不能为空'
			} else if (!reg.test(this.defaultView.password)) {
				this.defaultView.tipMessage = '请输入6位纯数字密码'
			} else {
				this.defaultView.tipMessage = ''
				this.defaultView.verify = true
			}

		},

		confirmModify: function () {

			if (!this.changePasswordView.password || !this.changePasswordView.surePassword) {
				Message({
					message: '密码输入不能为空',
					type: 'warning'
				})
				return
			}

			if (this.changePasswordView.password !== this.changePasswordView.surePassword) {
				Message({
					message: '两次密码输入不同,请重新输入',
					type: 'warning'
				})
				return
			}
			var params = {
				password: this.changePasswordView.surePassword,
				verificationCode: this.verificationView.verification.join('')
			}

			this.Axios.Post(this.URL.updatePsd.url, params).then(res => {
				var code = res.data.datas
				if (code == 10007) {
					this.view = 'successView'
					setTimeout(() => {
						this.deactivated()
					}, 1000)
				} else {
					Message({
						message: res.data.message || '密码修改失败',
						type: 'warning'
					})
					return
				}

			})

		},

		forgetPassword: function () {
			this.Axios.Post(this.URL.forgetPassword.url).then(res => {
				var massage = res.data.message
				if (massage.indexOf('验证码成功') > -1) {
					this.phoneNum = res.data.datas
					this.view = 'verificationView'
				}
			})

		}

		/* verificationView */

		/* changePasswordView */

		/* successView */
	}
}
</script>

<style lang='less' scoped>
.salaryPassword-dialog {
	input::-ms-clear{display:none;}
	input::-ms-reveal{display:none;}
  .defaultView {
    padding: 0 60px;
    overflow: hidden;
    .tipMessage {
      text-align: center;
      margin: 15px 0;
    }
    .password {
      text-align: center;
    }

    .forget {
      color: #027de5;
      cursor: pointer;
      text-align: right;
      float: right;
    }
  }

  .verificationView {
    text-align: center;
    p.tel {
      padding-top: 4px;
      color: #262626;
    }

    div.verification {
      padding: 25px 0;
    }

    p.sended {
      letter-spacing: 1px;
      strong {
        color: #262626;
      }
    }

    p.callHR {
      color: rgb(206, 206, 206);
    }
  }

  .changePasswordView {
    text-align: center;
    overflow: hidden;

    .password,
    .surePassword {
      width: 270px;
      margin: 10px auto;
      border-bottom: 1px solid rgb(206, 206, 206);
      height: 30px;
      line-height: 30px;
      overflow: hidden;
      label {
        width: 60px;
        float: left;
        margin-right: 10px;
      }
    }

    .button {
      padding-top: 20px;
    }
  }

  .successView {
    text-align: center;
    img.icon {
      display: inline-block;
      width: 120px;
      height: 120px;
    }

    p.config {
      letter-spacing: 1px;
      color: #333;
      padding-top: 10px;
      font-weight: bold;
    }
  }
}
</style>

<style lang='less'>
.salaryPassword-dialog {
  .el-input-group__append {
    cursor: pointer;
  }

  .blue {
    .el-input-group__append {
      background-color: #027de5 !important;
      border-color: #027de5 !important;
      color: #fff !important;
    }
  }

  .verificationView {
    div.verification {
      .verification-input {
        width: 35px;
        height: 30px;
        line-height: 1;
        margin: 0 8px;
        text-align: center;
        border: none;
        border-bottom: 1px solid rgb(206, 206, 206);
        outline: none;
        &::-webkit-outer-spin-button,
        &::-webkit-inner-spin-button {
          -webkit-appearance: none;
        }

        -moz-appearance: textfield;
        input {
          border: none;
          display: inline-block;
          border-bottom: 1px solid rgb(206, 206, 206);
          border-radius: 0;
          text-align: center;
        }
      }
    }
  }

  .changePasswordView {
    .changePassword-input {
      width: 200px;
      line-height: 1;
      text-align: center;
      float: left;
      input {
				
        border: none;
        display: inline-block;
        border-radius: 0;
        height: 30px;
			}
			input::-ms-clear{display:none;}
			input::-ms-reveal{display:none;}
    }

    .button {
      .el-button--primary {
        background-color: #027de5;
        border-color: #027de5;
      }
      .el-button--default {
        background-color: #a4b7c9;
        border-color: #a4b7c9;
        color: #fff;
      }
    }
  }
}
</style>
